<template>
  <el-dialog
    class="public-dialog"
    title="导入"
    width="720"
    :modelValue="modelValue"
    @close="handleClose"
    draggable
    align-center
  >
    <div>
      <VForm
        ref="form"
        :model="model"
        :fieldList="fieldList"
        :options="formOption"
        :rules="rules"
        :disabled="disabled"
        :originOption="optionsData"
      >
        <template #currency="{ value, input }">
          <CurrencySelect @update:model-value="input" :model-value="value" />
        </template>
        <template #bill_file="{ input, value }">
          <Upload
            label="Excel文件"
            require
            :modelValue="value"
            @update:modelValue="input"
          >
            <template #headRight>
              <el-button
                text
                type="primary"
                @click.stop="handleDownLoadTemplate"
              >
                <span>下载模板</span>
              </el-button>
            </template>
          </Upload>
        </template>
        <template #original_bill_file="{ input, value }">
          <Upload
            label="原始账单文件"
            require
            :modelValue="value"
            @update:modelValue="input"
          >
            <template #headRight>
              <div class="text-[12px] text-[#999] leading-[17px]">
                <span class="mr-[2px] iconfont icon-hint_line"></span>
                <span>只是用来存储文件</span>
              </div>
            </template>
          </Upload>
        </template>
        <template #bill_time="{ input, value }">
          <template v-if="props.type == 'MONTH'">
            <el-date-picker
              :modelValue="value"
              @update:modelValue="input"
              type="month"
              value-format="YYYY-MM"
              placeholder="请选择月"
            />
          </template>
          <template v-else>
            <WeekPicker :modelValue="value" @update:modelValue="input" />
          </template>
        </template>
      </VForm>
    </div>
    <template #footer>
      <div class="dialog-button">
        <el-button :disabled="loading" @click="handleClose(false)">
          {{ disabled ? "关闭" : "取消" }}
        </el-button>
        <el-button
          v-if="!disabled"
          type="primary"
          :loading="loading"
          @click="handleSave"
        >
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="jsx">
import { ElMessage } from "element-plus";
import VForm from "@/components/Form/index.vue";
import CurrencySelect from "@/components/CurrencySelect/index.vue";
import Upload from "@/components/Upload/index.vue";
import WeekPicker from "./components/weekPicker/index";
import { getImportUrl } from "@/api/public";
import { updateBills, createBills, billsDetail } from "../../api";

const props = defineProps({
  id: { type: [String, Number], default: "" },
  modelValue: { type: Boolean, default: false },
  disabled: { type: Boolean, default: false },
  optionsData: { type: Object, default: () => ({}) },
  type: { type: [String, Number], default: "" },
});

const emit = defineEmits(["update:modelValue", "refresh", "close"]);

const formOption = {
  labelPosition: "top",
  inline: true,
};

const rules = {
  bill_name: [{ required: true, message: "请输入账单名称", trigger: "blur" }],
  logistics_id: [{ required: true, message: "请选择物流商", trigger: "blur" }],
  // bill_cycle_type: [
  //   { required: true, message: "请选择账单类型", trigger: "blur" },
  // ],
  currency: [{ required: true, message: "请选择费用", trigger: "blur" }],
  // is_cabinet: [{ required: true, message: "请选择导入方式", trigger: "blur" }],
  // allocation_method: [{ required: true, message: "请选择分摊方式", trigger: "blur" }],
  bill_file: [{ required: true, message: "请上传Excel文件", trigger: "blur" }],
  original_bill_file: [
    { required: true, message: "请上传原始账单文件", trigger: "blur" },
  ],
};

const form = ref();
const model = ref({});
const loading = ref();
const orderData = ref();

const fieldList = [
  {
    field: "bill_name",
    label: "账单名称",
  },
  {
    field: "bill_time",
    label: "账单日期",
    slot: "bill_time",
    // type: "dateTimeRange",
    // itemProps: {
    //   startPlaceholder: "开始时间",
    //   endPlaceholder: "结束时间",
    // },
  },
  {
    field: "logistics_id",
    label: "物流商名称",
    type: "select",
    options: {
      labelKey: "logistics_name",
      valueKey: "logistics_id",
    },
    origin: "map.logistics",
  },
  // {
  //   field: "bill_cycle_type",
  //   label: "账单类型",
  //   type: "select",
  //   options: {
  //     labelKey: "label",
  //     valueKey: "value",
  //   },
  //   originField: "tc_bill_cycle_type",
  // },
  // {
  //   field: "allocation_method",
  //   label: "分摊方式",
  //   type: "select",
  //   options: {
  //     labelKey: "label",
  //     valueKey: "value",
  //   },
  //   originField: "tc_allocation_method",
  // },

  // {
  //   field: "currency",
  //   label: "币种",
  //   slot: "currency",
  //   style: { width: "180px" },
  // },
  // {
  //   field: "exchange_rate",
  //   label: "汇率",
  //   style: { width: "180px" },
  //   type: "inputNumber",
  //   min: 0.01,
  //   max: 9999999,
  // },
  { type: "br" },
  // {
  //   field: "is_cabinet",
  //   label: "导入方式",
  //   type: "radio",
  //   originField: "is_cabinet",
  // },
  // { type: "br" },
  {
    field: "bill_file",
    slot: "bill_file",
    full: true,
    style: { width: "100%" },
  },
  { type: "br" },
  {
    field: "original_bill_file",
    slot: "original_bill_file",
    style: { width: "100%" },
  },
  {
    field: "logistics_remark",
    label: "备注",
    type: "textarea",
    full: true,
    itemStyle: { width: "100%" },
    autosize: { minRows: 4, maxRows: 8 },
  },
];

watch(
  () => props.id,
  (val) => {
    if (val) {
      nextTick(() => {
        getDetail(val);
      });
    }
  }
);

const handleDownLoadTemplate = async () => {
  const { data } = (await getImportUrl({ type: "finance.initialFee" })) || {};
  const _url = data?.uri;
  if (_url) window.open(_url, "noopener", "noreferrer");
};

const getDetail = async (id) => {
  try {
    const { data } = await billsDetail({ id });

    const {
      original_bill_file,
      bill_file,
      bill_year_month,
      bill_ym_week,
      ...reset
    } = data;
    model.value = Object.assign({
      bill_time:
        props.type == "MONTH"
          ? bill_year_month
          : [bill_year_month, bill_ym_week],
      original_bill_file: original_bill_file
        ? [
            {
              name: original_bill_file.filename,
              url: original_bill_file.oss_path,
              source_name: original_bill_file.filename,
              response: {
                ...original_bill_file,
              },
            },
          ]
        : [],
      bill_file: bill_file
        ? [
            {
              name: bill_file.filename,
              url: bill_file.oss_path,
              source_name: bill_file.filename,
              response: {
                ...original_bill_file,
              },
            },
          ]
        : [],
      ...reset,
    });
    console.log(model.value);
  } catch (e) {
    orderData.value = {};
    console.error(e);
  }
};

const isEdit = computed(() => {
  return !!props.id;
});

const handleSave = async () => {
  try {
    const formInfo = await form.value.submit();

    const { bill_file, original_bill_file, bill_time, ...reset } = formInfo;
    const api = {
      edit: updateBills,
      add: createBills,
    };
    const { id } = props;

    console.warn(formInfo);
    const _prams = {
      id: id || undefined,
      ...reset,
      bill_year_month: props.type == "MONTH" ? bill_time : bill_time[0],
      bill_ym_week: props.type == "MONTH" ? undefined : bill_time[1],
      original_bill_file: original_bill_file?.[0].response,
      bill_file: bill_file?.[0].response,
      bill_cycle_type: props.type,
      bill_time: undefined,
    };
    console.log(_prams);
    const reqParams = _prams;
    const { code, message } = await api[isEdit.value ? "edit" : "add"](
      reqParams
    );
    if (code !== 200) {
      ElMessage.warning(message);
      return;
    }
    ElMessage.success(isEdit.value ? "修改成功" : "保存成功");
    handleClose(true);
  } catch (e) {
    if (e.toString().includes(false)) {
      ElMessage.warning("请检查表单信息");
    }
    console.error(e);
  } finally {
    loading.value = false;
  }
};

const handleClose = async (refresh) => {
  model.value = {};
  await nextTick();
  form.value.resetForm();
  emit("update:modelValue", false);
  emit("close");
  if (refresh) emit("refresh");
};
</script>
